<template>
	<view>
		<view class="container">
			<!-- <headerView :title='title' :backBtn="true"></headerView> -->
			<cu-custom bgColor="bg-gradual-orange" :isBack="true">
				<block slot="content">商家中心</block>
			</cu-custom>
			<!-- tab选择 -->
			<view class="tab-container">
				<view :class="['tab-item', { 'tab-item-active': selectTabIndex === index }]"
					v-for="(tab, index) in tabOptions" :key="index" @click="selectTab(index)">
					{{ tab.title }}
				</view>
			</view>

			<!-- 商家内容 -->
			<view class="merchant" v-if="merchantData.length">
				<view class="businesses-item" v-for="(merchant, index) in merchantData" :key="merchant.id"
					@tap="toDetail(merchant.id)">
					<view style="width: 170rpx;height: 170rpx;">
						<image class="item-left-image" :src="merchant.logo" mode="aspectFill"></image>
					</view>
					<view class="item-center-text">
						<view class="item-title">{{ merchant.short_name }}</view>
						<view class="item-phone">
							<image src="https://app.yycjkb.cn/index/fujiajia/phone.png" mode=""></image>
							{{ merchant.tel }}
						</view>
						<view class="item-buy">
							<view class="money-box">
								<image src="https://app.yycjkb.cn/index/fujiajia/定位.png" mode=""></image>
							</view>
							<view class="money-data">{{ merchant.address }}</view>
						</view>
					</view>
					<view class="item-right-icon">
						<image class="icon-red" src="https://app.yycjkb.cn/index/fujiajia/red.png" mode="aspectFill">
						</image>
						<view class="address">
							<!-- <image class="icon-address" src="https://app.yycjkb.cn/index/fujiajia/定位.png" mode="aspectFill"></image> -->
							{{ merchant.distance }}
						</view>
					</view>
				</view>
			</view>
			<!-- 加载状态提示 -->
			<view class="loading-status">
				<text v-if="loadingStatus === 'loading'">加载中...</text>
				<text v-if="loadingStatus === 'noMore'">没有更多了~</text>
			</view>

			<!-- 底部tabbar -->
			<!-- <tabBar :selectIndex="selectIndex"></tabBar> -->
		</view>
	</view>
</template>

<script>
	import headerView from "../components/header/header.vue";
	import tabBar from "../components/tabBar/index.vue";
	import api from "@/api/";

	export default {
		components: {
			headerView,
			tabBar
		},
		data() {
			return {
				title: "店铺列表",
				tabOptions: [],
				selectTabIndex: 0,
				merchantData: [],
				longitude: 0,
				latitude: 0,
				page: 1,
				loadingStatus: "more" // 加载状态：more|loading|noMore
			};
		},
		onReachBottom() { // 触底加载更多
			if (this.loadingStatus === 'more') {
				this.page += 1
				this.getMerchantList()
			}
		},
		async created() {
			await this.getLocation();
			await this.getCategories();
			await this.getMerchantList();
		},
		methods: {
			// 获取商家列表（新增分页逻辑）
			    async getMerchantList() {
			        const categoryId = this.tabOptions[this.selectTabIndex]?.id;
			        if (!categoryId) return;
			
			        // 阻止重复请求
			        if (this.loadingStatus === 'loading') return;
			        this.loadingStatus = 'loading';
			
			        const previousPage = this.page; // 记录请求前的页码
			
			        try {
			            const res = await api.shopList({
			                page: this.page,
			                cid: categoryId,
			                lng: this.longitude,
			                lat: this.latitude
			            });
			
			            if (res.code === 1) {
			                const newList = res.data.list || [];
			                
			                // 合并数据并去重
			                const mergedList = this.page === 1 ? newList : [...this.merchantData, ...newList];
			                this.merchantData = mergedList.filter((item, index, self) => 
			                    index === self.findIndex(t => t.id === item.id)
			                );
			
			                // 判断是否还有更多数据
			                this.loadingStatus = newList.length >= 25 ? 'more' : 'noMore';
			            }
			        } catch (error) {
			            console.error("获取商家列表失败", error);
			            this.loadingStatus = 'more';
			
			            // 失败时恢复之前的页码
			            this.page = previousPage;
			        }
			    },

			// 切换分类时重置分页
			async selectTab(index) {
				this.selectTabIndex = index;
				this.page = 1;
				this.merchantData = [];
				this.loadingStatus = 'more'
				await this.getMerchantList();
			},

			// 保持其他方法不变
			toDetail(id) {
				uni.navigateTo({
					url: `/pages/home/detail?id=${id}`
				});
			},
			async getLocation() {
				await uni.getLocation({
					success: (result) => {
						this.latitude = result.latitude;
						this.longitude = result.longitude;
					},
					fail: (error) => {
						console.error("获取位置失败", error);
					}
				});
			},
			async getCategories() {
				try {
					const res = await api.cateList();
					if (res.code === 1) {
						this.tabOptions = res.data.list;
					}
				} catch (error) {
					console.error("获取分类失败", error);
				}
			}
		}
	};
</script>


<style lang="less" scoped>
	.tab-container {
		display: flex;
		height: 100rpx;
		background-color: #fff;
		overflow-x: scroll;
		overflow-y: hidden;
		white-space: nowrap;

		&::-webkit-scrollbar {
			height: 0;
		}

		.tab-item {
			font-size: 30rpx;
			padding: 0 20rpx;
			min-width: auto; // 让宽度自适应内容
			height: 100%;
			line-height: 100rpx;
			cursor: pointer;
			position: relative;
			text-align: center;
			display: inline-block;
			white-space: nowrap; // 避免换行
			flex-shrink: 0; // 防止压缩导致重叠

			&.tab-item-active {
				color: #f76e00;

				&::before {
					content: "";
					position: absolute;
					left: 0;
					bottom: 0%;
					width: 100%;
					height: 6rpx;
					background-color: #ffd1aa;
				}
			}
		}

	}

	.merchant {
		.businesses-item {
			width: 100%;
			height: 204rpx;
			background-color: #fff;
			border-radius: 26rpx;
			margin-top: 20rpx;
			padding: 20rpx;
			display: flex;

			.item-left-image {
				width: 170rpx;
				height: 170rpx;
				border-radius: 10rpx;
			}

			.item-center-text {
				flex: 1; // 新增，让中间内容区域自动填充剩余宽度
				padding: 0 20rpx;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.item-phone {
					display: flex;
					align-items: center;
					color: #7b7b7b;
					padding-top: 14rpx;

					image {
						width: 23rpx;
						height: 23rpx;
						margin-right: 8rpx; // 增加图标与文字的间距
					}
				}

				.item-buy {
					display: flex;
					align-items: center;
					flex: 1; // 新增，填充可用空间
					overflow: hidden; // 防止内容溢出

					.money-box {
						width: 44rpx;
						height: 44rpx;
						margin-bottom: 0rpx; // 增加这个属性让图标下移
						// background-color: #ff9b45;
						display: flex;
						justify-content: center;
						align-items: center;
						border-bottom-left-radius: 6rpx;
						border-top-left-radius: 6rpx;

						image {
							width: 29rpx;
							height: 29rpx;
							margin-right: 15rpx;
						}
					}

					.money-data {
						flex: 1; // 新增，自动填充剩余宽度
						height: 40rpx;
						width: 350rpx;
						text-align: left;
						border-bottom-right-radius: 6rpx;
						border-top-right-radius: 6rpx;
						overflow: hidden;
						// font-size: 12rpx;
						// color: #ff9b45;
						// background-color: rgba(255, 155, 69, 0.2);
					}
				}
			}

			.item-right-icon {
				margin-left: auto;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.icon-red {
					width: 40rpx;
					height: 90rpx;
					margin-left: auto;
					margin-top: -10rpx;
				}

				.address {
					height: 75rpx;
					display: flex;
					align-items: center;
					color: #8a8a8a;

					image {
						height: 44rpx;
						width: 44rpx;
					}
				}
			}
		}
	}
	/* 新增加载状态样式 */
		.loading-status {
			padding: 30rpx 0;
			text-align: center;
			color: #999;
			font-size: 28rpx;
		}
</style>